﻿using System.Collections;
using System.Collections.Generic;
using System.Text;
using VideoCache.Server.Model;
using VideoCache.Server.BLL;

namespace System.Web.Mvc.Html
{
    public static class HtmlHelperExtension
    {
        #region Pager
        /// <summary>  
        /// 分页Pager显示  
        /// </summary>   
        /// <param name="html"></param>  
        /// <param name="currentPageStr">标识当前页码的QueryStringKey</param>   
        /// <param name="pageSize">每页显示</param>  
        /// <param name="totalCount">总数据量</param>  
        /// <returns></returns> 
        public static MvcHtmlString Pager(this HtmlHelper html, string currentPageStr, int pageSize, int totalCount)
        {
            string url = html.ViewContext.HttpContext.Request.Url.LocalPath;
            var queryString = html.ViewContext.HttpContext.Request.QueryString;
            int currentPage = 1; //当前页  
            var totalPages = (totalCount / pageSize) + ((totalCount % pageSize) > 0 ? 1 : 0); //总页数  
            var dict = new System.Web.Routing.RouteValueDictionary(html.ViewContext.RouteData.Values);
            var output = new System.Text.StringBuilder();

            foreach (string key in queryString.Keys)
            {
                if (queryString[key] != null && !string.IsNullOrEmpty(key))
                {
                    dict[key] = queryString[key];
                }
            }

            if (!string.IsNullOrEmpty(queryString[currentPageStr]))
            {
                int.TryParse(queryString[currentPageStr], out currentPage);
            }
            else
            {
                //获取 ～/Page/{page number} 的页号参数
                if (dict[currentPageStr] != null) int.TryParse(dict[currentPageStr].ToString(), out currentPage);
            }
            if (currentPage <= 0) currentPage = 1;

            output.Append("<ul>");

            if (totalPages > 1)
            {
                if (currentPage != 1)
                {
                    //处理首页连接  
                    dict[currentPageStr] = 1;
                    output.AppendFormat("<li>{0}</li>", html.RouteLink("<<", dict));
                }
                if (currentPage > 1)
                {
                    //处理上一页的连接  
                    dict[currentPageStr] = currentPage - 1;
                    output.AppendFormat("<li>{0}</li>", html.RouteLink("<", dict));
                }
                else
                {
                    output.Append("<li><span><<</span></li>");
                    output.Append("<li><span><</span></li>");
                }
                int currint = 5;
                for (int i = 0; i <= 10; i++)
                {
                    //一共最多显示10个页码，前面5个，后面5个  
                    if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                        if (currint == i)
                        {
                            //当前页处理  
                            output.Append("<li><span class='current'>" + currentPage + "</span></li>");
                        }
                        else
                        {
                            //一般页处理 
                            dict[currentPageStr] = currentPage + i - currint;

                            output.AppendFormat("<li>{0}</li>", html.RouteLink((currentPage + i - currint).ToString(), dict));
                        }
                }
                if (currentPage < totalPages)
                {
                    //处理下一页的链接 
                    dict[currentPageStr] = currentPage + 1;
                    output.AppendFormat("<li>{0}</li>", html.RouteLink(">", dict));
                }
                else
                {
                    output.AppendFormat("<li>{0}</li>", "<span>>></span>");
                    output.AppendFormat("<li>{0}</li>", "<span>></span>");
                }
                if (currentPage != totalPages)
                {
                    dict[currentPageStr] = totalPages;
                    output.AppendFormat("<li>{0}</li>", html.RouteLink(">>", dict));
                }
            }
            //output.AppendFormat("<li><span>第 {0} 页 / 共 {1} 页 记录总数：{2}</span></li>", currentPage, totalPages, totalCount);//这个统计加不加都行 
            output.Append("</ul>");
            return new MvcHtmlString(output.ToString());
        }
        #endregion

        public static MvcHtmlString VerifyCode(this HtmlHelper html)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<img class='verifycode' dataurl='/verifycode/' onclick=\"changeVerifyCode(this)\" align='absmiddle' />");

            return new MvcHtmlString(sb.ToString());
        }

        public static MvcHtmlString BithdaySelection(this HtmlHelper html, string field)
        {
            StringBuilder sbYear = new StringBuilder();

            sbYear.AppendLine("<select id=\"yearSelection\" name=\"yearSelection\">");
            sbYear.AppendLine("<option value=\"\">请选择年份</option>");
            for (int i = DateTime.Now.AddYears(-80).Year; i <= DateTime.Now.Year; i++)
            {
                sbYear.AppendLine("<option value=\"" + i + "\">" + i + "</option>");
            }
            sbYear.AppendLine("</select>");

            StringBuilder sbMonth = new StringBuilder();

            sbMonth.AppendLine("<select id=\"monthSelection\" name=\"monthSelection\">");
            sbMonth.AppendLine("<option value=\"\">请选择月</option>");
            for (int i = 1; i <= 12; i++)
            {
                sbMonth.AppendLine("<option value=\"" + i + "\">" + i + "</option>");
            }
            sbMonth.AppendLine("</select>");

            StringBuilder sbDay = new StringBuilder();

            sbDay.AppendLine("<select id=\"daySelection\" name=\"daySelection\">");
            sbDay.AppendLine("<option value=\"\">请选择日期</option>");
            for (int i = 1; i <= 31; i++)
            {
                sbDay.AppendLine("<option value=\"" + i + "\">" + i + "</option>");
            }
            sbDay.AppendLine("</select>");

            return new MvcHtmlString(sbYear.ToString() + sbMonth.ToString() + sbDay.ToString());
        }

        public static string GetDictionary(this HtmlHelper html, int dictionaryId)
        {
            DictionaryInfo info = DictionaryBLL.GetDictionary(dictionaryId);

            return info == null ? dictionaryId.ToString() : info.Name;
        }

        public static MvcHtmlString ShowText(this HtmlHelper html, string text, int length)
        {
            if (!string.IsNullOrEmpty(text) && text.Length > length)
            {
                return new MvcHtmlString(text.Substring(0, length - 3) + "...");
            }
            else
            {
                return new MvcHtmlString(text);
            }
        }

        public static MvcHtmlString ShowDictionaryHtmlTree(this HtmlHelper html, IEnumerable<DictionaryInfo> list)
        {
            if (list == null) return new MvcHtmlString(string.Empty);

            List<DictionaryInfo> dicList = new List<DictionaryInfo>();
            dicList.AddRange(list);
            StringBuilder sb = new StringBuilder();

            CreateChildernHtml(sb, 0, dicList);

            return new MvcHtmlString(sb.ToString());
        }

        private static void CreateChildernHtml(StringBuilder sb, int parentId, List<DictionaryInfo> list)
        {
            sb.Append("<ul>");
            foreach (var item in list.FindAll(p => p.ParentId == parentId))
            {
                sb.Append(string.Format("<li><label>{0}</label> <span><a href='/Dictionary/Edit/{1}'>编辑</a></span> <span><a href='/Dictionary/Delete/{1}' class='delete'>删除</a></span> <span>{2}</span>", item.Name, item.Id, item.ParentId));
                if (list.Exists(p => p.ParentId == item.Id))
                {
                    sb.Append("<ul>");
                    CreateChildernHtml(sb, item.Id, list);
                    sb.Append("</ul>");
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");
        }

        public static MvcHtmlString ShowDictionaryDropDownListTree(this HtmlHelper html, int selectedId)
        {
            List<DictionaryInfo> dicList = new List<DictionaryInfo>();
            dicList.AddRange(DictionaryBLL.FindAll(new DbMapping.Common.Conditions(), new DbMapping.Common.Orders()));
            StringBuilder sb = new StringBuilder();
            sb.Append("<option value='0'>根节点</option>");
            CreateChildernDropDownList(sb, 0, dicList, selectedId);

            return new MvcHtmlString(sb.ToString());
        }

        private static void CreateChildernDropDownList(StringBuilder sb, int parentId, List<DictionaryInfo> list, int selectedId)
        {
            foreach (var item in list.FindAll(p => p.ParentId == parentId))
            {
                sb.Append(string.Format("<option value='{0}' " + (selectedId == item.Id ? "selected='true'" : "") + "'>", item.Id));
                sb.Append(item.Name);
                sb.Append("</option>");
                if (list.Exists(p => p.ParentId == item.Id))
                {
                    CreateChildernDropDownList(sb, item.Id, list, selectedId);
                }
            }
        }
    }
}